package flexo.file.writer;

import java.io.BufferedWriter;

import flexo.file.*;

public class Xml extends Writer
{
	protected int depth;

	public void write(Node fileNode)
	{
		try
		{			
			BufferedWriter sw = createBufferedWriter(fileNode.name);
			depth = -1;
	
			for (int pos = 0; pos < fileNode.getChildrenCount(); pos++)
			{
				Node currentNode = fileNode.getChild(pos);
				write(currentNode,sw);
			}
	
			sw.close();
		}
		catch (Exception e)
		{
			writeError(fileNode.name);
		}
	}
	
	protected void write(Node current, BufferedWriter sw) throws Exception
	{
		depth++;

		String tabs = "";
		for (int i = 0; i < depth; i++)
		{
			tabs += "\t";
		}
		sw.write(tabs + "<" + current.name);

		for (int i = 0; i < current.getPropertyCount(); i++)
		{
			Property prop = current.getProperty(i);
			if (!prop.name.equals("text"))
			{
				sw.write(" " + prop.name + "=\"" + prop.getStringValue() + "\"");
			}
		}

		if (current.getChildrenCount() == 0 && current.getProperty("text") == null)
		{
			sw.write("/>");
			sw.newLine();
		}
		else
		{
			sw.write(">");
			if (current.getProperty("text") != null)
			{
				Property prop = current.getProperty("text");
				sw.write(prop.getStringValue());
			}
			else
			{					
				sw.newLine();
	
				for (int i = 0; i < current.getChildrenCount(); i++)
				{
					write(current.getChild(i),sw);
				}
				sw.write(tabs);
			}
			sw.write("</" + current.name + ">");
			sw.newLine();
		}
    
		depth--;
	}

}
